package net.simo.servicebook.service;

import java.util.List;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import net.simo.servicebook.model.Person;
import net.simo.servicebook.model.security.User;

// The @Stateless annotation eliminates the need for manual transaction demarcation
@Stateless
public class ClientRegistration {

	@Inject
	private Logger log;

	@Inject
	private EntityManager em;

	@Inject
	private Event<Person> memberEventSrc;
	
	private User user;

	public void register(Person person) throws Exception {
		log.info("Registering " + person.getPersonName());
		em.persist(person);
		memberEventSrc.fire(person);
	}

	public void editPerson(Person person) {
		em.merge(person);
	}

	public void deletePerson(Person person) {
		String hql = "FROM User WHERE person_id = :person_id";
		
		TypedQuery<User> query = em.createQuery(hql, User.class);
		query.setParameter("person_id", person.getPersonId());
		List<User> result = query.getResultList();
		
		user = new User();
		for (User user : result) {
			this.user = user;
		}
		user = em.find(User.class, user.getUserId());
		em.remove(user);
		person = em.find(Person.class, person.getPersonId());
		em.remove(person);
	}

}
